package org.blackcat.common;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by Duo Duo on 2016/12/26.
 */
public class DateUtils {


    public static final String DATE_FORMAT_SHORT = "yyyy-MM-dd";
    public static final String DATE_FORMAT_FULL = "yyyy-MM-dd HH:mm:ss";
    public static final String DAYE_FORMAT_MID = "yyyy-MM-dd HH:mm";


    /**
     *
     * @param field Calendar字段
     * @return 日历字段的值
     */
    public static final int getCalendar(int field){
        Calendar c = Calendar.getInstance();
        return c.get(field);
    }

    /**
     * 根据月数获取最大天数
     * @param date yyyy-MM-dd
     * @return
     */
    public static int getMaxDayByMonth(String date){
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            calendar.setTime(sdf.parse(date));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
    }

    /**
     *
     * @param dateStr
     * @param format
     * @return
     */
    public static Date parseDate(String dateStr,String format){
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        try {
            return sdf.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }


    public static String formatDate(Date date){
        if(date == null){
            return "";
        }
        SimpleDateFormat sdf=new SimpleDateFormat(DATE_FORMAT_SHORT);
        return sdf.format(date);
    }

    public static String formatDate(Date date,String format){
        if(date == null){
            return "";
        }
        String realFormat=format;
        if(null==format ||format.trim().length()==0){
            realFormat=DATE_FORMAT_SHORT;
        }
        SimpleDateFormat sdf=new SimpleDateFormat(realFormat);
        return sdf.format(date);
    }

}
